package com.mla.fastdfs.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.FdfsClientConstants;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.mla.fastdfs.commom.BaseException;
import com.mla.fastdfs.commom.UpLoadConstant;
import com.mla.fastdfs.pojo.UploadUpInfo;
import com.mla.fastdfs.pojo.User;
import com.mla.fastdfs.service.IUploadUpInfoService;
import com.mla.fastdfs.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


@Component
public class FastDFSClientUtil {

    @Value("${fdfs.reqHost}")
    private String reqHost;

    @Value("${fdfs.reqPort}")
    private String reqPort;

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private IUploadUpInfoService uploadUpInfoService;
    @Autowired
    private ThumbImageConfig thumbImageConfig; //创建缩略图   ， 缩略图访问有问题，暂未解决
    @Autowired
    private UserService userService;


    public String uploadFile(MultipartFile file, String aToken, String userId, Integer groupId, String anotherName, HttpServletRequest request) throws IOException {
        User user;
        if (userId!= null)
            user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getId, userId));
        else user = userService.getUser(aToken);

        if (user == null) {
            throw new BaseException("用户不存在");
        }
        UploadUpInfo info = new UploadUpInfo();
        info.setStartTime(DateUtil.getStrTime());
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);

        //String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
        storePath.setPath(UpLoadConstant.VISIT_URL + storePath.getPath());
        info.setIp(ToolUtil.getLocalIp(request))
                .setFileUrl(storePath.getPath())
                .setEndTime(DateUtil.getStrTime())
                .setFlag(null)
                .setFileName(file.getOriginalFilename())
                .setFileSize(file.getSize())
                .setPartNum(1)
                .setUid(user.getId())
                .setGroupId(groupId)
                .setAnotherName(anotherName)
        ;
        uploadUpInfoService.save(info);
        return storePath.getPath();
    }

    public void delFile(String filePath) {
        storageClient.deleteFile(filePath);

    }


    public InputStream download(String groupName, String path) {
        InputStream ins = storageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>() {
            @Override
            public InputStream recv(InputStream ins) throws IOException {
                // 将此ins返回给上面的ins
                return ins;
            }
        });
        return ins;
    }

    /**
     * 封装文件完整URL地址
     *
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        return storePath.getPath();
    }
}